package com.hukun.ssm1110.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class FileController {

    @RequestMapping("/uploadPage")
    public String uploadPage() {
        return "upload";
    }


    @RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model) {

        String info = "";
        for (MultipartFile uploadFile :
                fileUpload) {
            String dirpath = "D:\\upload";
            File dirfile = new File(dirpath);
            //判断是否有目标文件夹
            if (!dirfile.exists()) {
                //没有就创建
                dirfile.mkdir();
            }
            String originalFilename = uploadFile.getOriginalFilename();
            String fileName = dirpath + "\\" + originalFilename;
            //创建上传文件
            File newFile = new File(fileName);
            try {
                //上传文件
                uploadFile.transferTo(newFile);
                info = "上传成功";
            } catch (IOException e) {
                info = "上传失败";
                throw new RuntimeException(e);
            }
        }
        model.addAttribute("uploadStatus", info);

        return "upload";
    }

    @RequestMapping("/toDownload/{filename}")
    public String toDownload(
            @PathVariable(value = "filename", required = false) String filename,
            Model model) {
        model.addAttribute("image", filename);
        return "download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String filename, Model model, HttpServletRequest request) {
//        要下载的文件的源头文件夹
        String source = "D:\\upload\\";
        String filePath = source + filename;
        File file = new File(filePath);
        if (!file.exists()) {
            model.addAttribute("info", "服务器没有该文件");
            return null;
        } else {
            try {
                //设定下载的协议头
                HttpHeaders httpHeaders = new HttpHeaders();
                String downloadFilename = getFilename(request, filename);
                httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                httpHeaders.setContentDispositionFormData("attachment", downloadFilename);
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }


    }

    /**
     * 支持下载中文文件名
     *
     * @param request
     * @param filename
     * @return
     * @throws Exception
     */

    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                return URLEncoder.encode(filename, "UTF-8").replace("+", " ");
            }
        }
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }

}
